# 生成题库
import random
import copy


def generate_sudoku_board():
    # 创建一个9x9的二维列表，表示数独棋盘
    board = [[0] * 9 for _ in range(9)]
    print("初始board",board)

    # 递归函数，用于填充数独棋盘的每个单元格
    def filling_board(row, col):
        # 计算下一个单元格的行和列索引
        next_row = row if col < 8 else row + 1
        next_col = (col + 1) % 9

        # 获取当前单元格在小九宫格中的索引
        box_row = row // 3
        box_col = col // 3

        for num in range(1,10):
            # 检查行、列、小九宫格是否已经存在相同的数字
            if num not in board[row] and all(board[i][col] != num for i in range(9)) and all(
                            num != board[i][j] for i in range(box_row * 3, box_row * 3 + 3) for j in
                            range(box_col * 3, box_col * 3 + 3)):
                board[row][col] = num

                # 递归填充下一个单元格
                if filling_board(next_row, next_col):
                    return True

                # 回溯，将当前单元格重置为0
                board[row][col] = 0

        return False

    # 填充数独棋盘
    filling_board(0, 0)

    return board

# level数字越大代表游戏难度越大
def create_board(level):
    board = generate_sudoku_board()
    board1 = copy.deepcopy(board)
    for i in range(81):
        row = i // 9  # 向下取整除
        col = i % 9  # 取模运算，返回除法的余数
        #print(row,col)
        if random.randint(0, 9) < level:
            board1[row][col] = 0
    return (board, board1)

v = create_board(5)
print("数独答案：",v[0])
print("待计算的数独：",v[1])